package cn.virens.web.controller.manage.base;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.virens.common.RequestUtil;
import cn.virens.database.mysql.model.sys.SysUser;
import cn.virens.database.mysql.model.sys.SysUserBind;
import cn.virens.service.inter.sys.SysUserService;
import cn.virens.web.common.BaseUserController;
import cn.virens.web.components.shiro.ShiroRealmInterface;
import cn.virens.web.components.shiro.comm.SessionUtil;

@RequestMapping("/manage/base")
@Controller("ManageBasePageContorller")
public class BasePageContorller extends BaseUserController {
	private @Autowired ShiroRealmInterface mShiroRealmInterface;
	private @Autowired SysUserService mSysUserService;

	public BasePageContorller() {
		super("/manage/base");
	}

	@RequestMapping("user/view.jspx")
	public String userView(HttpServletRequest request, HttpServletResponse response, Model model) {
		return returnUrl("user/view");
	}

	@RequestMapping("user/edit.jspx")
	public String userEdit(HttpServletRequest request, HttpServletResponse response, Model model) {
		return returnUrl("user/edit");
	}

	@ResponseBody
	@RequestMapping("user/edit/save.json")
	public Model userEditSave(SysUser record, HttpServletRequest request, Model model) {
		if (mSysUserService.update(record, getUserUuid(request)) != null) {
			return useSession(request, (session) -> {
				SessionUtil.clearLoginInfo(session);

				return renderSuccess(model, "保存成功");
			});
		} else {
			return renderFail(model, "保存失败");
		}
	}

	@RequestMapping("user/pwd.jspx")
	public String userPwd(HttpServletRequest request, HttpServletResponse response, Model model) {
		return returnUrl("user/pwd");
	}

	@ResponseBody
	@RequestMapping("user/pwd/save.json")
	public Model userPwdSave(HttpServletRequest request, HttpServletResponse response, Model model) {
		String passwordRetry = RequestUtil.getValueStr(request, "password_retry");
		String password = RequestUtil.getValueStr(request, "password");

		if (password != null && password.equals(passwordRetry)) {
			SysUserBind bind = new SysUserBind();
			bind.setUuid(getUserUuid(request));
			bind.setPasswordSrc(password);

			// 更新成功后 ,清理Shiro账号密码缓存
			if (mSysUserService.bindUpdate(bind) != null) {
				mShiroRealmInterface.clearAuthorizationInfo(getSubject(request));
				mShiroRealmInterface.clearAuthenticationInfo(getSubject(request));
			} else {
				return renderFail(model, "修改失败");
			}
		} else {
			return renderFail(model, "两次密码不同");
		}

		return renderSuccess(model, "修改成功");
	}
}
